# -*- coding: UTF-8 -*-
# @Time : 2022-02-07 22:25
# @User：My.
# @File : Operate.py
from selenium import webdriver
from Base.ExcelData import Data
from TestData.ExcelConfig import TestSteps, Elements, CaseData, TestCases
from Base.BasePage import Action, screenshot_allure
from Utils.LogUtil import my_log
from Conf import conf
from Utils.YamlUtil import YamlReader
import allure

# data = Data(conf.data_file)
# run_case = data.run_list()


def sccrenshot_allure():
    pass


class Operate(): #Action

    def __init__(self, driver):
        """
        driver = webdriver.Firefox(executable_path="D:\geckodriver.exe")
        driver.get("")
        super().__init__(driver)
        """
        self.driver = driver
        self.log = my_log('Operate')

    """
        def test_step(self):
            data = Data('../../TestData/TestData.xlsx')
            # 获取可执行的测试用例
            run_list = data.run_list()
            print(run_list)
            # 根据测试用例执行步骤
            # 第一条测试用例
            run_case = run_list[0][0]
            tc_id = run_case[TestSteps.STEP_TC_ID]
            steps = data.get_step_by_tc_id(tc_id)
            for step in steps:
                print('执行步骤{0}:'.format(step))
                operates = step[TestSteps.STEP_OPERATE]
                # 获取by, value
                elements = step[TestSteps.STEP_ELEMENT_NAME]
                element = data.get_elements_by_element(step[TestSteps.STEP_TC_ID], elements)
                print(element)
                value = element[Elements.ELE_VALUE]
                by = element[Elements.ELE_BY]
                if operates == 'click':
                    Action(self.driver).click_btn(by, value)
                elif operates == 'text':
                    # 获取by, value, send_value数据内容
                    send_value = step[TestSteps.STEP_DATA]
                    data_input = run_case[CaseData.DATA_VALUE]
                    print(data_input)
                    # user=admin;pwd=a123456 分割数据
                    res = {}
                    res_1 = str(data_input).split(';')
                    print(res_1)
                    for i in res_1:
                        print(i)
                        res_2 = str(i).split('=')
                        print(res_2)
                        print("res_2[0]=" + res_2[0])
                        print("res_2[1]=" + res_2[1])
                        res[res_2[0]] = res_2[1]
                    print(res)
                    # send_value 获取最后的send
                    send = res[send_value]
                    print('send===' + send)
                    Action(self.driver).send_keys(by, value, send)
                elif operates == 'verify_toast':
                    # 获取get_toase具体信息
                    # 获取期望结果
                    text = run_case[CaseData.DATA_EXPECT_RESULT]
                    # print(text)
                    # toase结果验证
                    toase = Action(self.driver).get_toase(text)
                    print(toase)
    """

    def get_key(self, name):
        """
        获取key.yml文件，映射key
        :param name:
        :return:
        """
        key_file = conf.key_yml
        reader = YamlReader(key_file).data()
        value = reader[name]
        return value

    def str_to_dict(self, content):
        """
        字符串转字典
        :return:
        """
        # user=aaaa;pwd=123456 分割数据
        res = {}
        res_1 = str(content).split(';')
        for i in res_1:
            res_2 = str(i).split('=')
            res[res_2[0]] = res_2[1]
        return res

    def step_run(self, run_case):
        self.log.info('执行用例内容：{}'.format(run_case))
        self.step(run_case)
    
    @screenshot_allure
    def step(self, data, run_case):
        # 获取可执行的测试用例
        # run_list = data.run_list()
        # print(run_list)
        # 根据测试用例执行步骤
        # 第一条测试用例
        # run_case = run_list[0][0]
        tc_id = run_case[TestSteps.STEP_TC_ID]
        steps = data.get_step_by_tc_id(tc_id)

        # allure报告
        # feature 备注（登录功能）
        allure.dynamic.feature(run_case[TestCases.CASE_NOTE])
        # story 描述（登录）
        allure.dynamic.story(run_case[TestCases.CASES_DESC])
        # title 用例ID+用例名称
        allure.dynamic.title(run_case[CaseData.DATA_TC_ID]+'-'+run_case[CaseData.DATA_CASE_NAME])

        for step in steps:
            # print('执行步骤{0}:'.format(step))
            # operates = step[TestSteps.STEP_OPERATE]
            # 获取by, value
            elements = step[TestSteps.STEP_ELEMENT_NAME]
            element = data.get_elements_by_element(step[TestSteps.STEP_TC_ID], elements)
            self.log.debug('执行步骤{0}'.format(element))
            # 获取操作步骤
            operate = self.get_key(step[TestSteps.STEP_OPERATE])

            if operate:
                # 定义方法字典
                param_value = dict()
                # 根据getattr判断执行方法
                action_methon = getattr(Action(self.driver), operate)
                self.log.debug('关键字：{}'.format(operate))
                # 定义方法参数
                value = element[Elements.ELE_VALUE]
                by = element[Elements.ELE_BY]
                send_value = step[TestSteps.STEP_DATA]
                expect = run_case[CaseData.DATA_EXPECT_RESULT]
                param_value['by'] = by
                param_value['value'] = value
                param_value['expect'] = expect

                # 判断输入内容 字符转换
                if send_value:
                    # 获取by, value, send_value数据内容
                    data_input = run_case[CaseData.DATA_VALUE]
                    send = self.str_to_dict(data_input)
                    param_value['send'] = send[send_value]
                # 步骤
                with allure.step(step[TestSteps.STEP_NAME]):
                    action_methon(**param_value)
            else:
                self.log.error('没有operate信息{0}'.format(operate))


if __name__ == '__main__':
    test = Operate()
    # test.test_step()
    list_case = [
        {'TC_ID': 'TC_Login', 'CASE_ID': 'Case_002', '是否运行': 'y', '用例名称': '登录成功', '测试数据': 'user=aaaa;pwd=123456',
         '期望结果': ''}]
    data = Data(conf.data_file)
    test.step(data, {'TC_ID': 'TC_Login', 'CASE_ID': 'Case_002', '是否运行': 'y', '用例名称': '登录成功',
                     '测试数据': 'user=admin;pwd=a123456',
                     '期望结果': ''})
